# -*- coding:utf-8 -*-
import re
import threading
import time
import schedule
from flask import Flask, request, jsonify

from catAPI import *
from utils import Alarm
from utils import ImageUtil
from utils import SearchIp
from utils import Translation
from utils import Weibo
from utils import music
from utils import yqcx
from utils.CatMyUtil import *
from utils import NiuBiWord
from utils import Power
from utils import SEXxnxx

app = Flask(import_name=__name__, static_url_path="/static", static_folder="static")
basedir = os.path.abspath(os.path.dirname(__file__))
basedirImg = 'F:\\IMAGES\\image'
ip_address = socket.getfqdn(socket.gethostname())
Local_Addr = socket.gethostbyname(ip_address)

# 放置下载文件的路径
app.config['DOWNLOAD_FOLDER'] = os.path.join(basedir, 'picture')


@app.route('/', methods=['GET'])
def index():
    return "<h2>这是一个API测试站</h2>"


musicing = 0

talkingUser = {}


@app.route('/api', methods=['POST', 'GET'])
def msgApi():
    if request.method == 'POST':
        bean = {}
        bean['file_url'] = None
        bean['wx_type'] = request.form.get("type")  # 数据类型
        bean['msg'] = request.form.get("msg")  # 发送内容
        bean['to_wxid'] = request.form.get("from_wxid")  # 1级来源id（比如发消息的人的id）
        bean['from_name'] = request.form.get("from_name")  # 1级来源昵称（比如发消息的人昵称）
        bean['final_from_wxid'] = request.form.get("final_from_wxid")  # 2级来源id（群消息事件下，1级来源为群id，2级来源为发消息的成员id，私聊事件下都一样）
        bean['final_nickname'] = request.form.get("final_from_name")  # 2级来源昵称
        bean['robot_wxid'] = request.form.get("robot_wxid")  # 当前登录的账号（机器人）标识id
        bean['parameters'] = request.form.get("parameters")  # 附加参数（暂未用到，请忽略）
        bean['ws_time'] = request.form.get("time")  # 请求时间(时间戳10位版本)
        try:
            bean['file_url'] = request.form.get("file_url")  # 如果是文件消息（图片、语音、视频、动态表情），这里则是可直接访问的网络地址，非文件消息时为空
        except:
            raise TypeError("请使用 http-api 2.4+以上的版本")
        print(bean.get('to_wxid'))
        print(bean.get('final_nickname'))

        #全局方法开始
        #获取微信id
        getwxid(bean)
        print(bean.get("msg"))
        #全局方法结束
        if (Power.hasPowerHome(bean.get('to_wxid'), bean.get('final_from_wxid'))):
            print("进入方法 能力 绿色 ！！！！！！！！！！")
            menu(bean)
            moyu(bean)
            searchIP(bean)
            yiqing(bean)
            yiqingDetail(bean)
            fanyi(bean)
            hotSerach(bean)
            musics(bean)
            alarm(bean)
        elif (Power.hasPower(bean.get('to_wxid'), bean.get('final_from_wxid'))):
            print("进入方法 能力！！！！！！！！！！")
            try:
                if bean.get('wx_type') == "100":  # 私聊消息
                    menu(bean)
                    moyu(bean)
                    cqls(bean)
                    gxls(bean)
                    mjx(bean)
                    lsj(bean)
                    lsjr18(bean)
                    xxxr18(bean)
                    searchIP(bean)
                    yiqing(bean)
                    yiqingDetail(bean)
                    fanyi(bean)
                    hotSerach(bean)
                    musics(bean)
                    alarm(bean)
                    # 定制丛
                    musicimg(bean)
                elif bean.get('wx_type') == "200":  # 群聊消息
                    menu(bean)
                    moyu(bean)
                    mjx(bean)
                    lsj(bean)
                    lsjr18(bean)
                    xxxr18(bean)
                    searchIP(bean)
                    yiqing(bean)
                    yiqingDetail(bean)
                    fanyi(bean)
                    hotSerach(bean)
                    musics(bean)
                    pass
                else:
                    pass
            except Exception as e:
                print(e)
                # send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), "哎呀！[苦涩]我被你搞的精疲力尽")
        else:
            pass

    else:
        return f"GET访问测试页面，本机地址 http://{Local_Addr}"  # 此处的测试地址应该是http://localhost:8074/复制到可爱猫功能-》HTTP多语言对-》消息回调地址
    return jsonify({"code": 200, "data": "result ok"})


# 方法区域
#全局方法
def getwxid(bean):
    key = "龙顺我的ID"
    if bean.get('msg') == key:
        send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), bean.get('to_wxid'))
    return key

#权限方法
def menu(bean):
    if bean.get('msg') == "龙顺帅哥":
        menu = "帅哥来了！ 我能力：\n"
        listnl = [moyu(bean)
                  # , cqls(bean)#
                  # , gxls(bean)
            , mjx(bean)
            , lsj(bean)
            , lsjr18(bean)
            , xxxr18(bean)
            , searchIP(bean)
            , yiqing(bean)
            , yiqingDetail(bean)
            , fanyi(bean)
            , hotSerach(bean)
            , musics(bean)
            , alarm(bean)]
        for nl in listnl:
            menu += (nl + "\n")
        print(menu)
        send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), menu)


def moyu(bean):
    key = "摸鱼"
    if bean.get('msg') == key:
        send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), NiuBiWord.getNbw())
    return key


def cqls(bean):
    key = "重启龙顺"
    if bean.get('msg') == key:
        print("进来了")
        requests.get(
            "http://127.0.0.1:5001/restartCat?robot_wxid=" + bean.get('robot_wxid') + "&to_wxid=" + bean.get('to_wxid'))
        send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), "已发送重启！")
    return key


def gxls(bean):
    key = "更新龙顺"
    if bean.get('msg') == key:
        print("进来了")
        get = requests.get("http://127.0.0.1:5001/updateCat")
        print(get.text)
        send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), get.text)
    return key


def mjx(bean):
    key = "mjx"
    if bean.get('msg') == key:
        pathi = basedirImg + '\\mjx\\'
        pname = saveImage("https://api.ghser.com/tao", pathi)
        pic_path = pathi + pname
        print(pic_path)
        send_image_msg(bean.get('robot_wxid'), bean.get('to_wxid'), pic_path)
    return key


def lsj(bean):
    key = "lsj"
    if bean.get('msg') == key:
        lsj = ImageUtil.lsj()
        for url in lsj:
            pathi = basedirImg + '\\lsj\\'
            pname = saveImage(url, pathi)
            pic_path = pathi + pname
            print(pic_path)
            send_image_msg(bean.get('robot_wxid'), bean.get('to_wxid'), pic_path)
    return key


def lsjr18(bean):
    key = "lsjr18"
    if bean.get('msg') == key:
        lsj = ImageUtil.lsjr18()
        for url in lsj:
            pathi = basedirImg + '\\lsj18\\'
            pname = saveImage(url, pathi)
            pic_path = pathi + pname
            print(pic_path)
            send_image_msg(bean.get('robot_wxid'), bean.get('to_wxid'), pic_path)
    return key


def xxxr18(bean):
    key = "xxxr18"
    if bean.get('msg') == key:
        parf = SEXxnxx.getGifPath(bean.get('to_wxid'))
        pathi = basedirImg + '\\xxxr18\\'
        pname = saveImage(parf, pathi)
        pic_path = pathi + pname
        print(pic_path)
        send_image_msg(bean.get('robot_wxid'), bean.get('to_wxid'), pic_path)
    return key


# 模糊匹配区

def searchIP(bean):
    key = "查IP#"
    p = re.compile('^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$')
    if key in bean.get('msg'):
        uChaGroup = bean.get('msg').split('#')
        if p.match(uChaGroup[1]):
            SearchIp.cx_ip(uChaGroup[1], robot_wxid, to_wxid)
        else:
            send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), "请填写正确的IP地址！")
    elif p.match(bean.get('msg')):
        SearchIp.cx_ip(bean.get('msg'), robot_wxid, to_wxid)
    return key


def yiqing(bean):
    key = "疫情#"
    if key in bean.get('msg'):
        yqnames = bean.get('msg').split('#')
        send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), yqcx.searchyq(yqnames[1]))
    return key


def yiqingDetail(bean):
    key = "疫情详细#"
    if key in bean.get('msg'):
        yqnames = bean.get('msg').split('#')
        send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), yqcx.searchyqDetail(yqnames[1]))
    return key


def fanyi(bean):
    key = "翻译#"
    if key in bean.get('msg'):
        yqnames = bean.get('msg').split('#')
        send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), Translation.tranmain(yqnames[1]))
    return key


def hotSerach(bean):
    key = "热搜#"
    if key in bean.get('msg'):
        yqnames = bean.get('msg').split('#')
        send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), Weibo.wbrs(yqnames[1]))
    return key


def musics(bean):
    try:
        key = "音乐#"
        if key in bean.get('msg'):
            global musicing
            if (musicing == 0):
                musicing = 1
                yqnames = bean.get('msg').split('#')
                send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), "开始查询，预计一分钟内！" + yqnames[1])
                path = music.getFile(yqnames[1])
                musicing = 0
                if (path != None):
                    send_file_msg(bean.get('robot_wxid'), bean.get('to_wxid'), path)
                    pass
                else:
                    send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), yqnames[1] + " 没找到 》《！")
            else:
                send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), "查音乐忙碌中，等会！")
        return key
    except:
        musicing == 0
        send_text_msg(bean.get('robot_wxid'), bean.get('to_wxid'), "干崩了！")


def alarm(bean):
    key = "提醒#"
    if key in bean.get('msg'):
        Alarm.alarm(bean.get('robot_wxid'), bean.get('to_wxid'), bean.get('final_from_wxid'),
                    bean.get('final_nickname'), bean.get('msg'))
    return key


def musicimg(bean):
    key = "music.126.net"
    key1 = "y.qq.com"
    if bean.get('msg').find(key) != -1:
        send_image_msg(bean.get('robot_wxid'), bean.get('to_wxid'),
                       bean.get('msg').replace("param=", "param=500y500&aa="))
    elif bean.get('msg').find(key1) != -1:
        send_image_msg(bean.get('robot_wxid'), bean.get('to_wxid'), bean.get('msg').replace("R300x300", "R500x500"))
    return key


# 能力区结束


# 定时发热搜
def job():
    print("I'm working...")
    for twx in Power.getTimeHot():
        send_text_msg(Power.getRebot(), twx, Weibo.wbrs(20))


# 提醒
def job1():
    Alarm.mainfun()


def schemain():
    schedule.every().day.at("08:00").do(job)
    schedule.every(1).seconds.do(job1)
    while True:
        time.sleep(1)
        schedule.run_pending()


if __name__ == "__main__":
    t = threading.Thread(target=schemain)
    t.start()
    app.run(host="0.0.0.0", port=5000)
